package Utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Scanner;

import lib.In;

public class ReadWriteFiles {

	public static void main(String[] args) {
		ReadWriteFiles f = new ReadWriteFiles();
		String file ="file:///C:/a.txt";
		String[] arr = f.readPath(file);
		for (int i = 0; i < arr.length; i++) {
           System.out.println(arr[i]);
		}
	}

	private String charsetName = "UTF-8";
	private Locale usLocale = new Locale("zh", "CN");

	public String readAll(Scanner scanner) {
		if (!scanner.hasNextLine()) {
			return null;
		}
		return scanner.useDelimiter("\\A").next();
	}

	public String[] readPath(String path) {
		Scanner scanner;
		try {
			// first try to read file from local file system
			File file = new File(path);
			if (file.exists()) {
				scanner = new Scanner(file, charsetName);
				scanner.useLocale(usLocale);
			}
			// next try for files included in jar
		 	URL url = getClass().getResource(path);
			// or URL from web
			if (url == null) {
				url = new URL(path);
			}
		
			URLConnection site = url.openConnection();
			InputStream is = site.getInputStream();
			scanner = new Scanner(new BufferedInputStream(is), charsetName);
			scanner.useLocale(usLocale);
			
			return readAll(scanner).trim().split("\\s+");
		} catch (IOException ioe) {
			System.err.println("Could not open " + path);
		}
		return null;

	}

}
